#include <vector>
#include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <stdlib.h>
#include <stdio.h>

#include <cstring>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <list> 
#include "all.h"

using namespace std;

std::vector<std::string> getFiles(const std::string &folder) {
  std::vector<std::string> files;
  std::list<std::string> subfolders;
  subfolders.push_back(folder);

  while (!subfolders.empty()) {
    std::string current_folder(subfolders.back());

    if (*(current_folder.end() - 1) != '/') {
      current_folder.push_back('/');
    }

    DIR* pdir = opendir(current_folder.c_str());

    subfolders.pop_back();

    if (!pdir) {
      continue;
    }

    dirent* dir = NULL;

    while ((dir = readdir(pdir)) != NULL) {
      // iterates the current folder, search file & sub folder
      struct stat st;

      if (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, "..")) {
        // must ignore . & ..
        continue;
      }

        string strCut = dir->d_name;
        string prefix;
        size_t posStart = strCut.find(".");
        prefix = strCut.substr(posStart + 1, strCut.size());
        if (prefix != "jpg")
            continue;

      std::string file_path;

      file_path.append(current_folder.c_str());
      file_path.append(dir->d_name);

      if (lstat(file_path.c_str(), &st) < 0) {
        // perror("lstat");
        continue;
      }

      if (S_ISDIR(st.st_mode)) {
	      // will search sub folder
	      std::string subfolder(current_folder);
	      subfolder.append(dir->d_name);
	      subfolders.push_back(subfolder.c_str());
      } else {
        // it's a file
        files.push_back(file_path);
      }
    }  // while
    closedir(pdir);
  }

  return files;
}


int rename_iter(string path)
{
    static int i = 0;
    std::vector<std::string> fileVec = getFiles(path);
    for (vector<string>::iterator it = fileVec.begin();
	    it != fileVec.end(); ++it){
            
        std::stringstream ss(std::stringstream::in | std::stringstream::out);
    	ss << path.c_str() << "/" << "rr_" << i++ << ".jpg";

        cout << "old: " << (*it).c_str() << "new: " <<ss.str().c_str() << endl;
        rename((*it).c_str(), ss.str().c_str());
        
    }

    return 0;
}